package com.github.bobjoy.java.thread;

/**
 * http://www.cnblogs.com/DreamSea/archive/2012/01/16/2263844.html
 */
public class ThreadDemo implements Runnable {

    private int num = 10;

    public void firstMethod() {
        synchronized (this) {
            this.num += 100;
            System.out.println(this.num);
        }
    }

    /**
     * sleep不会释放对象锁：secondMethod -> firstMethod；wait则会释放对象锁：firstMethod -> secondMethod
     * wiat()必须放在synchronized block中，否则会在program runtime时扔出”java.lang.IllegalMonitorStateException“异常。
     */
    public void secondMethod() throws InterruptedException {
        synchronized (this) {
            Thread.sleep(2000);
//            this.wait(2000);
            this.num *= 200;
        }
    }

    @Override
    public void run() {
        this.firstMethod();
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadDemo td = new ThreadDemo();
        Thread thread = new Thread(td);
        thread.start();
        td.secondMethod();
    }
}
